package com.sphd.emanu.mvp;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;


import com.sphd.emanu.R;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.utils.SimpleDividerDecoration;
import com.squareup.picasso.Picasso;
import com.wzutils.L;
import com.wzutils.SPUtils;

import java.io.File;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public abstract class MVPBaseFragment<V extends BaseView, T extends BasePresenterImpl<V>> extends Fragment implements BaseView {
    public View rootView;
    public T mPresenter;
    public Context context;
    private SwipeRefreshLayout myRefreshLayout;
    private boolean isVisible = false;//当前Fragment是否可见
    private boolean isInitView = false;//是否与View建立起映射关系
    private boolean isFirstLoad = true;//是否是第一次加载数据
    private SparseArray<View> mViews;
    public SweetAlertDialog sweetAlertDialog;
   public View emptyView;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        mvpBaseActivity = (MVPBaseActivity) getActivity();
        context = getContext();
        mPresenter = getInstance(this, 1);
        mPresenter.attachView((V) this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(getLayoutId(), container, false);
        emptyView=View.inflate(context,R.layout.layout_emptyview,null);
        mViews = new SparseArray<>();
        initView();
        isInitView = true;
        lazyLoadData();
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        L.e("isVisibleToUser " + isVisibleToUser + "   " + this.getClass().getSimpleName());
        if (isVisibleToUser) {
            isVisible = true;
            lazyLoadData();

        } else {
            isVisible = false;
        }
        super.setUserVisibleHint(isVisibleToUser);
    }

    public void setImage(ImageView imageView, String url) {
        Picasso.with(context)
                .load(url)
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .into(imageView);
    }

    public void setImage(ImageView imageView, String url,int srcId) {
        Picasso.with(context)
                .load(url)
                .placeholder(srcId)
                .error(srcId)
                .into(imageView);
    }

    public MultipartBody.Part prepareFilePart(String partName, String path) {
        File file = new File(path);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
    }

    private void lazyLoadData() {
        if (isFirstLoad) {
            L.e("第一次加载 " + " isInitView  " + isInitView + "  isVisible  " + isVisible + "   " + this.getClass().getSimpleName());
        } else {
            L.e("不是第一次加载" + " isInitView  " + isInitView + "  isVisible  " + isVisible + "   " + this.getClass().getSimpleName());
        }
        if (!isFirstLoad || !isVisible || !isInitView) {
            L.e("不加载" + "   " + this.getClass().getSimpleName());
            return;
        }

        L.e("完成数据第一次加载" + "   " + this.getClass().getSimpleName());
        initData();
        isFirstLoad = false;
    }

    public boolean isCanLook(List<Moudle> moudles, Integer menuId) {
        boolean flag = false;
        for (Moudle moudle : moudles) {
            if (moudle.getMoudleId().equals(menuId)) {
                flag = moudle.getPermissionInfo().isLookOver();
                break;
            }
        }
        return flag;
    }

    public boolean isCanDo(List<Moudle> moudles, Integer menuId) {
        boolean flag = false;
        for (Moudle moudle : moudles) {
            if (moudle.getMoudleId().equals(menuId)) {
                flag = moudle.getPermissionInfo().isOperation();
                break;
            }
        }
        return flag;
    }


    /**
     * 加载页面布局文件
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 让布局中的view与fragment中的变量建立起映射
     */
    protected abstract void initView();

    /**
     * 加载要显示的数据
     */
    protected abstract void initData();

    /**
     * fragment中可以通过这个方法直接找到需要的view，而不需要进行类型强转
     *
     * @param viewId
     * @param <E>
     * @return
     */
    protected <E extends View> E findView(int viewId) {
        if (rootView != null) {
            E view = (E) mViews.get(viewId);
            if (view == null) {
                view = (E) rootView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return view;
        }
        return null;
    }

    public Object get(String key, Object defaultObject) {
        return SPUtils.get(context, key, defaultObject);
    }

    public void put(String key, Object defaultObject) {
        SPUtils.put(context, key, defaultObject);
    }

    public void remove(String key) {
        SPUtils.remove(context, key);
    }

    public void setRefresh(SwipeRefreshLayout myRefreshLayout) {
        this.myRefreshLayout = myRefreshLayout;
        myRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light, android.R.color.holo_red_light,
                android.R.color.holo_orange_light, android.R.color.holo_green_light);
    }

    public void setRecy(RecyclerView recy) {

        recy.setHasFixedSize(true);
        recy.setLayoutManager(new LinearLayoutManager(context));

    }

    public void setRecyWithDecorationBySelf(RecyclerView recy, int colorId, int dimenId) {

        recy.setHasFixedSize(true);
        recy.setLayoutManager(new LinearLayoutManager(context));
        recy.addItemDecoration(new SimpleDividerDecoration(context, colorId, dimenId));
    }

    public void setRecyWithDecoration(RecyclerView recy) {
        recy.setHasFixedSize(true);
        recy.setLayoutManager(new LinearLayoutManager(context));
        recy.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
    }

    public void setGRecy(RecyclerView recy, int i) {

        recy.setHasFixedSize(true);

        recy.setLayoutManager(new GridLayoutManager(context, i));

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null)
            mPresenter.detachView();
    }

    @Override
    public Context getContext() {
        return super.getContext();
    }

    public void showProgressDialog() {
        if (sweetAlertDialog == null) {
            sweetAlertDialog = new SweetAlertDialog(context, SweetAlertDialog.PROGRESS_TYPE);
            sweetAlertDialog.setTitleText("加载中……");
        }
        sweetAlertDialog.show();
    }

    @Override
    public void dissProgressDialog() {
        if (sweetAlertDialog != null) {
            sweetAlertDialog.dismiss();
        }
        if (myRefreshLayout != null) {
            if (myRefreshLayout.isRefreshing()) {
                myRefreshLayout.setRefreshing(false);
            }
        }
    }

    public <T> T getInstance(Object o, int i) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass()
                    .getGenericSuperclass())).getActualTypeArguments()[i])
                    .newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

    public AlertDialog getDialogBuilder(View view, String title, String PositiveButton, String NegativeButton) {
        return new AlertDialog.Builder(context).setView(view).setTitle(title).setPositiveButton(PositiveButton, null).
                setNegativeButton(NegativeButton, null).show();
    }

    public void toast(Object o) {
        if (o instanceof Integer) {
            Toast.makeText(context, (Integer) o, Toast.LENGTH_SHORT).show();
        } else if (o instanceof CharSequence) {
            Toast.makeText(context, (CharSequence) o, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, o + "", Toast.LENGTH_SHORT).show();
        }

    }

}
